class ListNode {
    int val;
    //套定义ListNode类型
    ListNode next;
    ListNode(int x) { val = x; }
}

public class KthNodeFromEnd {
    public static void main(String[] args) {
        // 创建一个测试链表 1 -> 2 -> 6 -> 3 -> 4 -> 5 -> 6
        ListNode head = new ListNode(1);
        head.next = new ListNode(2);
        head.next.next = new ListNode(6);
        head.next.next.next = new ListNode(3);
        head.next.next.next.next = new ListNode(4);
        head.next.next.next.next.next = new ListNode(5);
        head.next.next.next.next.next.next = new ListNode(6);

        int k = 3;
        //调用内部类中的方法
        ListNode result = Solution.endNode(head, k);

        // 打印结果链表
        while (result != null) {
            System.out.print(result.val + " ");
            result = result.next;
        }
    }

    static class Solution {
        public static ListNode endNode(ListNode head, int k) {
            if (head == null || k <= 0) {
                return null;
            }

            ListNode tool = head;
            int length = 1;

            while (tool.next != null) {
                tool = tool.next;
                length++;
            }

            for (int i = length - k; i > 0; i--) {
                head = head.next;
            }

            return head;
        }
    }
}

